/**
 * New node file
 */
$(function(){
	"use strict";
	
	window.WebSocket = window.WebSocket || window.MozWebSocket;
	
	var connection = new WebSocket('ws://192.168.0.28:8000');
	
	connection.onopen = function(){
		console.log('connection');
	};
	
	connection.onerror = function(error){
		console.log('connection error');	
	};
	
	connection.onmessage = function(message){
		console.log('message : ' + message);
		console.log(message);
		try{
			var json = JSON.parse(message.data);
			console.log('트라이');
			console.log(json);
		}catch(e){
			console.log('not json message : ' + message.data);
			var innerHTML = "";
			innerHTML += "<div id='"+id+"' style='position:absolute; left:0px; top:0px; border: 1px solid blue'>"; 
			innerHTML += "<span style='cursor:hand; cursor:pointer; border: 1px solid black' onmousedown='startMove(event,"+id+")'>aaaaaaaaaaaaaaaaaaaaa</span>";
			innerHTML += "<span id='close' style='position:absolute; overflow: hidden' title='닫기'>닫기..</span>";
			innerHTML += "<div>";
			innerHTML += "<table border='1' width='200px' height='150px'>";
			innerHTML += "<tr>";    
			innerHTML += "	<td><input type='button' id='btn'/><input type='hidden' name='resId' value='"+$(this).attr('id')+"' /> 받는사람 : "+$(this).attr('id')+"</td>";			    	
			innerHTML += "</tr>";			    		
			innerHTML += "<tr>";	    	
			innerHTML += "	<td>";    	
			innerHTML += "		<textarea id='m_text' rows='10' cols='25' style='resize:none;'></textarea>";			    		
			innerHTML += "	</td>";							
			innerHTML += "</tr>";			
			innerHTML += "</table></div></div>";    	
			$('#chatDiv').append(innerHTML);		
			return;
		}
		
		if(json.type === 'message'){
			addMessage(json.data.text);
		}
	};
	
	$('#chatDiv').delegate('#btn','click',function(){
		//console.log($('#m_text').val());
		var msg = $('#m_text').val();
		var reqId = $('input[name=epid]').val(); 
		var resId = $('input[name=resId]').val();
		var ip = '192.168.0.8';
		var json = JSON.stringify({reqId:reqId,resId:resId,msg:msg,ip:ip,regDate:"11"});
		connection.send(json);
		
	});
	
	function addMessage(message){
		console.log('addMessage : ' + message);
	}
});